from django.shortcuts import render
from df_user.islogin import islogin
# Create your views here.
from df_cart.models import *
from df_goods.models import *
from django.http import JsonResponse


@islogin
def index(request):
    # 从session中获取当前用户的id
    uid = request.session.get('user_id')
    # 根据id搜索当前用户放入购物车中的品种
    carts = CartInfo.objects.filter(user_id=uid)

    context = {'cart':1,
               'carts':carts,
               'title':'购物车'
               }
    return render(request,'df_cart/cart.html',context)

def add(request, gid, count):
    # 从session中获取用户id
    uid = request.session.get('user_id')
    count = int(count) # 字符串转整数

    # 从数据库中根据用户id和商品id查询数量
    carts = CartInfo.objects.filter(user_id=uid, goods_id=gid)
    # carts的数量要么是0 要么是1（查询有多少行）
    if len(carts) >= 1:
        # 购物车中已经有该商品
        cart = carts[0]
        cart.count += count
        cart.save()
    else:
        # 购物车中还没有该商品
        cart = CartInfo()
        cart.user_id = uid
        cart.goods_id = gid
        cart.count = count
        cart.save()

    # 通过json返回购物车中商品的总数量
    result = CartInfo.objects.filter(user_id=uid).count()
    return JsonResponse({'count':result})

def edit(request, cart_id, count):
    try:
        cart = CartInfo.objects.get(id=cart_id)
        cart.count = int(count)
        cart.save()
        data = {'ok':0}
    except Exception as e:
        print(e)
        data = {'ok':1}

    return JsonResponse(data)


def delete(request, cart_id):
    try:
        cart = CartInfo.objects.get(id=cart_id)
        cart.delete()
        data = {'ok': 0}
    except Exception as e:
        print(e)
        data = {'ok': 1}

    return JsonResponse(data)